package _17_剑指Offer;

import _17_剑指Offer.datastrcute.TreeNode;

import java.util.*;

public class _32_剑指Offer从上到下打印二叉树III {

    List<List<Integer>> results = new ArrayList<>();

    // DFS遍历，当前DFS层数也就是数组下标元素
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return results;

        dfs(root, 0);
        return results;
    }

    private void dfs(TreeNode root, int depth) {
        if (root == null) return;

        if (depth == results.size()) {
            results.add(new ArrayList<>());
        }

        if ((depth & 1) == 0) {
            results.get(depth).add(root.val);
        } else {
            results.get(depth).add(0, root.val);
        }

        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }

    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        if (root == null) return results;

        // 双端队列
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int resultSize = results.size();
            if ((resultSize & 1) == 1) {
                // 把当前队列中所有元素遍历
                for (int i = queue.size(); i > 0; i--) {
                    TreeNode node = queue.pollLast();
                    list.add(node.val);

                    if (node.right != null) queue.offerFirst(node.right);
                    if (node.left != null) queue.offerFirst(node.left);
                }
            } else {
                for (int i = queue.size(); i > 0; i--) {
                    TreeNode node = queue.poll();
                    list.add(node.val);

                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
            }
            results.add(list);
        }
        return results;
    }
}
